import axios from 'axios'
import {Toast} from 'vant';
import store from '@/store'
import {getToken} from '@/utils/Storage'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    // baseURL: '/apis',
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 300000 // request timeout
})
service.defaults.headers.post['Content-Type'] = 'application/json'
// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        if (config.method === 'post') {
            config.data = JSON.stringify(config.data)
        }

        if (store.getters.token) {
            config.headers['Authorization'] = getToken()
        }
        return config
    },

    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data

        if (res.code !== 0) {
            if (res.code === 9999 || res.code === 2010) {
                console.log('提示错误')
                Toast({
                    message: res.msg || 'Error',
                    type: 'fail',
                    icon: 'none',
                    duration: 3 * 1000
                });
            }
            return Promise.reject(res || 'Error')
        } else {
            return res
        }
    },
    error => {
        console.log('err' + error) // for debug
        Toast({
            message:error,
            type: 'fail',
            icon: 'none',
            duration: 3 * 1000
        });
        return Promise.reject(error)
    }
)

export default service
